package com.imooc.service.impl;

import com.imooc.bo.UserBo;
import com.imooc.enums.Sex;
import com.imooc.mapper.UsersMapper;
import com.imooc.pojo.Users;
import com.imooc.service.UserService;
import com.imooc.utils.DateUtil;
import com.imooc.utils.MD5Utils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * @Author wangke
 * @Description TODO
 * @Date 2021/7/5 19:38
 * @Version 1.0
 */

@Service
public class UsersServiceImpl implements UserService {

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private Sid sid;

    @Override      //校用户名是否存在
    @Transactional(propagation=Propagation.SUPPORTS)
    public Boolean queryUsernameIsExist(String userName) {
        Example usersExample = new Example(Users.class);
        Example.Criteria usersExampleCriteria = usersExample.createCriteria();//构建查询条件
        usersExampleCriteria.andEqualTo("username",userName);
        Users user = usersMapper.selectOneByExample(usersExample);

        return user==null?false:true;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Users createUser(UserBo userBo) {
        //创建用户对象
        Users users = new Users();
        //生成全局唯一id
        users.setId(sid.nextShort());
        //密码加密
        try {
            users.setPassword(MD5Utils.getMD5Str(userBo.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置默认信息保存
        users.setFace("0");
        users.setNickname(userBo.getUsername());
        users.setUsername(userBo.getUsername());
        users.setBirthday(DateUtil.stringToDate("1900-01-01"));
        users.setSex(Sex.secret.type);
        users.setCreatedTime(new Date());
        users.setUpdatedTime(new Date());
        usersMapper.insert(users);
        return users;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS) //事务支持
    public Users QueryUserForLogin(String userName, String password) {
        Example example = new Example(Users.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("username",userName);

        criteria.andEqualTo("password",password);

        Users users = usersMapper.selectOneByExample(example);

        return users;

    }
}
